package com.sora.handler;

import com.sora.entity.RpcRequest;
import com.sora.entity.RpcResponse;
import com.sora.enumeration.ResponseCode;
import com.sora.provider.ServiceProvider;
import com.sora.provider.ServiceProviderImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @Classname: RequestHandler
 * @Description: 请求的处理
 * @Author: Stonffe
 * @Date: 2023/4/30 17:36
 */
public class RequestHandler {
    private static final Logger logger = LoggerFactory.getLogger(RequestHandler.class);
    private static final ServiceProvider serviceProvider;
    static {
        serviceProvider = new ServiceProviderImpl();
    }
    /**
     * 对真正调用的方法进行一层包装
     * @param rpcRequest
     * @return
     */
    public Object handle(RpcRequest rpcRequest) {
        Object service = serviceProvider.getServiceProvider(rpcRequest.getInterfaceName());
        return invokeTargetMethod(rpcRequest, service);
    }

    /**
     * 利用反射调用方法并返回结果
     * @param rpcRequest
     * @param service
     * @return 这个方法的返回值
     * @throws InvocationTargetException
     * @throws IllegalAccessException
     */
    private Object invokeTargetMethod(RpcRequest rpcRequest, Object service) {
        Object result;
        try {
            Method method = service.getClass().getMethod(rpcRequest.getMethodName(), rpcRequest.getParamType());
            result = method.invoke(service, rpcRequest.getParameters());
            logger.info("服务:{} 成功调用方法:{}", rpcRequest.getInterfaceName(), rpcRequest.getMethodName());
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            return RpcResponse.fail(rpcRequest.getRequestId(), ResponseCode.METHOD_NOT_FOUND);
        }
        return result;
    }
}
